package ru.arriah.servicedesk.web.chief.action;

import java.io.IOException;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.common.web.action.DumbAction;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalHome;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.LoginException;

public class LoginAction extends DumbAction {
   protected EmployeeManagerLocalHome clientManagerHome;

   public LoginAction() throws NamingException {
      super();

      clientManagerHome =
         Utils.getEmployeeManagerHomeInterface();
   }

   public String execute(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {
      try {
         EmployeeManagerLocalObject employeeManager =
            clientManagerHome.create();

         String login = request.getParameter("login");
         String password = request.getParameter("password");
         
         int clientId = employeeManager.authorize(login, password, 1);
         
         employeeManager.remove();
         
         request.getSession().setAttribute("userId", clientId);
         request.getSession().setAttribute("role", "chief");
         request.getSession().setAttribute("_sideBarListType", "displayRequestsList");
         
         return actionMapping.getSuccessTarget();
      } catch (Exception e) {
         handleException(e, "execute");
         throw new LoginException("ErrorMessage.illegalLogin");
      }
   }
}